#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "hal.h"
#include "config.h"
#include "ioAT89S52.h"

volatile bool g_UARTReady = false; 

void FeedWatchDog()
{
  WDTRST = 0x1E;
  WDTRST = 0xE1;
}



/*
P1.4 up
p1.6 down
p1.3 left
p1.7 right
p1.5 center
*/

void InitTimer1()
{
  //Config timer 1
  TMOD_bit.C_T1 = 0;  // Set as timer
  TMOD_bit.GATE1 = 0; //TR1�������� ֹͣ
  TMOD_bit.M01 = 0;
  TMOD_bit.M11 = 1;
  //TL1 = 0;
  TH1 = 0xfd;
  //����Timer 1
  TCON_bit.TR1 = 1;
}

void InitUART(void)
{
  //UART
  PCON_bit.SMOD = 1; //����baud X 2

  //8BIT MODE2
  SCON_bit.SM0 = 0;
  SCON_bit.SM1 = 1;

  SCON_bit.SM2 = 0; // �رնദ����
  SCON_bit.REN = 1;

  //Config Use timer 1 as closk source
  T2CON_bit.TCLK = 0; // Use Timer1
  T2CON_bit.RCLK = 0;

  InitTimer1();
  // ��UART�ж�
  IE_bit.ES = 1;
  
  g_UARTReady = true;
}



void SendSync(const char *msg)
{
  const char* p = msg;
  while(*p != '\0'){
    while(!g_UARTReady);
    g_UARTReady = false;
    SBUF = *p;
    p++;
  }
}


#define STATUS_READYTORECEIVE 0
#define STATUS_NEWDATA 1
#define STATUS_RECEIVETOOFAST 2

volatile uint8_t receivedData = 0;
volatile uint8_t status = 0;

SERIAL_STATUS GetSerialData(uint8_t *data){
  SERIAL_STATUS ret = SERIAL_SUCCESS;
  *data = receivedData;
  if(status | STATUS_READYTORECEIVE != 0 ){
    ret = SERIAL_NO_DATA;
  }
  else if(status | STATUS_RECEIVETOOFAST != 0) {
    ret = SERIAL_TOOSLOW;
  }
  status = STATUS_READYTORECEIVE;
}



#pragma vector = sio_ti
//#pragma vector = sio_ri
__interrupt void serial_RI(void)
{
  if (SCON_bit.RI == 1)/* clear reception flag for next reception *//* if reception occur */
  {
    SCON_bit.RI = 0;        
    uint8 uart_data = SBUF; /* Read receive data */
    if( STATUS_READYTORECEIVE == status){
      status |= STATUS_NEWDATA;
      receivedData = uart_data;
    }  
    else {
      status |= STATUS_RECEIVETOOFAST;
      receivedData = uart_data;
    }
  }
  
  if (SCON_bit.TI == 1)
  {
    SCON_bit.TI = 0; // clear emission flag for next emission
    g_UARTReady = true;    
  }
  
}
